package cn.autowired.exam.controller;

import cn.autowired.exam.base.CommonResponse;
import cn.autowired.exam.dto.StudentPaperDto;
import cn.autowired.exam.dto.StudentPaperLayui;
import cn.autowired.exam.entity.Paper;
import cn.autowired.exam.entity.Student;
import cn.autowired.exam.entity.StudentPaper;
import cn.autowired.exam.service.PaperService;
import cn.autowired.exam.service.StudentPaperService;
import cn.autowired.exam.service.StudentService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 *   @description : StudentPaper 控制器
 *   ---------------------------------
 */
@RestController
    @RequestMapping("/studentPaper")
public class StudentPaperController extends AbstractController {
private final Logger logger=LoggerFactory.getLogger(StudentPaperController.class);

    @Autowired
    public StudentPaperService studentPaperService;

    @Autowired
    public PaperService paperService;

    @Autowired
    public StudentService studentService;

    /**
     *  预约考试
     * @param studentNo
     * @param paperId
     * @return
     */
    @RequestMapping("/requestForExam")
    public ResponseEntity requestForExam(String studentNo,Integer paperId){
        StudentPaper studentPaper = new StudentPaper();
        studentPaper.setIsDone(0);
        studentPaper.setStudentNo(studentNo);
        studentPaper.setPaperId(paperId);
        HashMap<Object, Object> hashMap = Maps.newHashMap();
        boolean flag = false;
        try{
             flag = studentPaper.insertOrUpdate();

        }catch(Exception e){
            hashMap.put("msg","error");
            hashMap.put("code",-1);
            return ResponseEntity.ok(hashMap);
        }
        if (flag){
            hashMap.put("msg","success");
            hashMap.put("code",0);
            return ResponseEntity.ok(hashMap);
        } else {
            hashMap.put("msg","error");
            hashMap.put("code",-1);
            return ResponseEntity.ok(hashMap);
        }
    }




    /**
     * 获取所有的答题情况
     * @return
     */
    @GetMapping("/allStudentPaper")
    public ResponseEntity allStudentPaper(){
        List<StudentPaper> studentPapers = studentPaperService.selectList(new EntityWrapper<StudentPaper>().eq(StudentPaper.Field.isDone,1));
        ArrayList<Object> list = Lists.newArrayList();
        for (StudentPaper studentPaper : studentPapers) {
            HashMap<Object,Object> layui = Maps.newHashMap();
            layui.put("id",studentPaper.getId());
            Paper paper = paperService.selectById(studentPaper.getPaperId());
            layui.put("title",paper.getTitle());
            Student student = studentService.selectOne(new EntityWrapper<Student>().eq(Student.Field.studentNo, studentPaper.getStudentNo()));
            if (student!=null){
                layui.put("studentNo",student.getStudentNo());
                layui.put("name",student.getName());
                layui.put("major",student.getMajor());
                layui.put("score",studentPaper.getScore());
                layui.put("comment",studentPaper.getComment());
            }

            list.add(layui);
        }

        HashMap<Object, Object> hashMap = Maps.newHashMap();
        hashMap.put("msg","success");
        hashMap.put("code",0);
        hashMap.put("count",studentPapers.size());
        hashMap.put("data",list);
        return ResponseEntity.ok(hashMap);
    }

    @PostMapping("/addComment")
    public ResponseEntity addCommentById(Integer id,String comment){
        StudentPaper studentPaper =new StudentPaper();
        StudentPaper selectById = studentPaper.selectById(id);
        selectById.setComment(comment);
        selectById.updateById();
        return ResponseEntity.ok("success");
    }
    /**
     * 查看指定学号下的学生的试卷详情,
     * @param studentNo 学号
     * @return 包含试卷的详情的列表
     */
    @GetMapping("/paperOfStudentDetail/{studentNo}")
    public ResponseEntity paperOfStudentDetail(@PathVariable String studentNo){
        List<StudentPaper> studentPapers = studentPaperService.selectList(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo));
        List<StudentPaperLayui> list = new LinkedList<>();

        for (StudentPaper studentPaper : studentPapers) {
            StudentPaperLayui studentPaperLayui = new StudentPaperLayui();
            studentPaperLayui.setComment(studentPaper.getComment());
            studentPaperLayui.setId(studentPaper.getId());
            studentPaperLayui.setIsDone(studentPaper.getIsDone());
            studentPaperLayui.setScore(studentPaper.getScore());
            Paper paper = paperService.selectById(studentPaper.getPaperId());
            studentPaperLayui.setTitle(paper.getTitle());
            studentPaperLayui.setAuthor(paper.getAuthor());
            studentPaperLayui.setPaperId(paper.getId());
            studentPaperLayui.setQuestionCount(paper.getQuestionCount());
            list.add(studentPaperLayui);
        }
        HashMap<Object, Object> hashMap = Maps.newHashMap();
        hashMap.put("msg","success");
        hashMap.put("code",0);
        hashMap.put("count",list.size());
        hashMap.put("data",list);
        return ResponseEntity.ok(hashMap);
    }



    @GetMapping("/paperOfStudent/{studentNo}")
    public ResponseEntity paperOfStudent(@PathVariable String studentNo){
        List<StudentPaper> studentPapers = studentPaperService.selectList(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo));
        List<StudentPaperDto> list = new LinkedList<>();

        for (StudentPaper studentPaper : studentPapers) {
            StudentPaperDto studentPaperDto = new StudentPaperDto();
            studentPaperDto.setComment(studentPaper.getComment());
            studentPaperDto.setId(studentPaper.getId());
            studentPaperDto.setIsDone(studentPaper.getIsDone());
            studentPaperDto.setScore(studentPaper.getScore());
            Paper paper = paperService.selectById(studentPaper.getPaperId());
            studentPaperDto.setPaper(paper);
            list.add(studentPaperDto);
        }
        return ResponseEntity.ok(list);
    }


    /**
     * 查看指定学号下已完成的学生的试卷
     * @param studentNo 学号
     * @return 包含试卷的详情的列表
     */
    @PostMapping("/paperOfStudent/{studentNo}")
    public ResponseEntity unCompletedPaperOfStudent(@PathVariable String studentNo){
        List<StudentPaper> studentPapers = studentPaperService.selectList(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.isDone,1));
        List<StudentPaperDto> list = new LinkedList<>();
        for (StudentPaper studentPaper : studentPapers) {
            StudentPaperDto studentPaperDto = new StudentPaperDto();
            studentPaperDto.setComment(studentPaper.getComment());
            studentPaperDto.setId(studentPaper.getId());
            studentPaperDto.setIsDone(studentPaper.getIsDone());
            studentPaperDto.setScore(studentPaper.getScore());
            Paper paper = paperService.selectById(studentPaper.getPaperId());
            studentPaperDto.setPaper(paper);
            list.add(studentPaperDto);
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 查看指定学号下未完成的学生的试卷
     * @param studentNo 学号
     * @return 包含试卷的详情的列表
     */
    @PutMapping("/paperOfStudent/{studentNo}")
    public ResponseEntity completedPaperOfStudent(@PathVariable String studentNo){
        List<StudentPaper> studentPapers = studentPaperService.selectList(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.isDone,0));
        List<StudentPaperDto> list = new LinkedList<>();
        for (StudentPaper studentPaper : studentPapers) {
            StudentPaperDto studentPaperDto = new StudentPaperDto();
            studentPaperDto.setComment(studentPaper.getComment());
            studentPaperDto.setId(studentPaper.getId());
            studentPaperDto.setIsDone(studentPaper.getIsDone());
            studentPaperDto.setScore(studentPaper.getScore());
            Paper paper = paperService.selectById(studentPaper.getPaperId());
            studentPaperDto.setPaper(paper);
            list.add(studentPaperDto);
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 增加指定学号下的学生的试卷
     * @param studentNo 学号
     * @param paperId 试卷id
     * @return 成功or失败
     */
    @PostMapping("/addPaper")
    public ResponseEntity addPaper(String studentNo,int paperId){
       StudentPaper studentPaper = new StudentPaper();
       studentPaper.setPaperId(paperId);
       studentPaper.setStudentNo(studentNo);
       studentPaper.setIsDone(0);
        boolean isInsert = studentPaper.insert();
        return isInsert?ResponseEntity.ok("success"):ResponseEntity.badRequest().build();
    }

    /**
     *  删除指定学号下的试卷
     * @param studentNo 学号
     * @param paperId 试卷Id
     * @return
     */
    @PostMapping("/deletePaper")
    public ResponseEntity deletePaper(String studentNo,int paperId){
        StudentPaper studentPaper = new StudentPaper();
        studentPaper.setStudentNo(studentNo);
        studentPaper.setPaperId(paperId);
        boolean isDelete = studentPaper.deleteById();
        return isDelete?ResponseEntity.ok("success"):ResponseEntity.badRequest().build();
    }

    /**
     * 完成试卷后标识已经完成的测试
     * @param studentNo 学号
     * @param paperId 试卷ID
     * @return
     */
    @PostMapping("/complete")
    @SuppressWarnings("all")
    public ResponseEntity paperCompleted(String studentNo,int paperId){
        StudentPaper existStudentPaper = studentPaperService.selectOne(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.paperId, paperId));
        if (existStudentPaper!=null){
            Integer isDone = existStudentPaper.getIsDone();
            if (isDone==0){
                existStudentPaper.setIsDone(1);
                existStudentPaper.updateById();
            }else {
                return ResponseEntity.badRequest().build();
            }
        }
        return ResponseEntity.ok("success");
    }

    /**
     *  重新完成测试
     * @param studentNo 学号
     * @param paperId 试卷id
     * @return 成功or失败
     */
    @PostMapping("/reComplete")
    @SuppressWarnings("all")
    public ResponseEntity paperReCompleted(String studentNo,int paperId){
        StudentPaper existStudentPaper = studentPaperService.selectOne(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.paperId, paperId));
        if (existStudentPaper!=null){
            Integer isDone = existStudentPaper.getIsDone();
            if (isDone==1){
                existStudentPaper.setIsDone(0);
                existStudentPaper.updateById();
            }else {
                return ResponseEntity.badRequest().build();
            }
        }
        return ResponseEntity.ok("success");
    }

    /**
     *  打分
      * @param studentNo 学号
     * @param paperId 试卷id
     * @param answer 答案( 形式 A,B,C,D )
     * @return
     */
    @PostMapping("/setScore")
    public ResponseEntity setScore(String studentNo,int paperId,String answer){
        String[] split = answer.split(",");
        int score = 0;
        for (String s : split) {
            switch (s.toUpperCase()){
                case "A":
                    score+=3;
                break;
                case "B":
                    score+=2;
                break;
                case "C":
                    score+=1;
                break;
                case "D":
                    score+=0;
                break;
                default:
                    score+=0;
            }
        }
        StudentPaper existStudentPaper = studentPaperService.selectOne(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.paperId, paperId));
        if (existStudentPaper != null) {
            existStudentPaper.setScore(score);
            existStudentPaper.setIsDone(1);
            existStudentPaper.insertOrUpdate();
            return ResponseEntity.ok(CommonResponse.ok());
        }else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 增加或更新评论
     * @param studentNo 学号
     * @param paperId 试卷ID
     * @param comment 评论
     * @return
     */
    @PostMapping("/addOrUpdateComment")
    public ResponseEntity addOrUpdateComment(String studentNo,int paperId,String comment) {
        StudentPaper existStudentPaper = studentPaperService.selectOne(new EntityWrapper<StudentPaper>()
                .eq(StudentPaper.Field.studentNo, studentNo)
                .eq(StudentPaper.Field.paperId, paperId));
        if (existStudentPaper != null) {
            existStudentPaper.setComment(comment);
            existStudentPaper.insertOrUpdate();
            return ResponseEntity.ok("success");
        }else {
            return ResponseEntity.badRequest().build();
        }
    }


}